package com.jfirer.redisserver.command.impl;

import com.jfirer.jnet.common.api.ProcessorContext;
import com.jfirer.redisserver.RedisCore;
import com.jfirer.redisserver.command.Command;
import com.jfirer.redisserver.command.CommandType;
import com.jfirer.redisserver.datatype.BytesWrapper;
import com.jfirer.redisserver.datatype.RedisString;
import com.jfirer.redisserver.resp.BulkString;
import com.jfirer.redisserver.resp.Resp;
import com.jfirer.redisserver.resp.SimpleString;

public class SetEx implements Command
{
    private BytesWrapper key;
    private int          seconds;
    private BytesWrapper value;

    @Override
    public CommandType type()
    {
        return CommandType.setex;
    }

    @Override
    public void setContent(Resp[] array)
    {
        key = ((BulkString) array[1]).getContent();
        seconds = Integer.parseInt(((BulkString) array[2]).getContent().toUtf8String());
        value = ((BulkString) array[3]).getContent();
    }

    @Override
    public void handle(ProcessorContext ctx, RedisCore redisCore)
    {
        RedisString redisString = new RedisString();
        redisString.setValue(value);
        redisString.setTimeout(System.currentTimeMillis() + (seconds * 1000));
        redisCore.put(key, redisString);
        ctx.fireWrite(SimpleString.OK);
    }
}
